﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MenuUsuarioMapa.aspx.cs"
    Inherits="VemTransporte.Views.UsuarioTransporte.MenuUsuarioMapa" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="header1" runat="server">
    <title>..:: STI ::..</title>
    <link href="../../Content/Estilo/stylo.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/menuUsuario_files/css3menu1/style.css" rel="stylesheet"
        type="text/css" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var geocoder;
        var map;
        var intervalFuncao;
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var gerouRoutaParada;
        var IdLinhaUsuarioLogado = '<%=Session["IdLinhaUsuarioLogado"] %>';
        var IdUsuarioLogado = '<%=Session["IdUsuarioLogado"] %>';

        $(document).ready(function () {
            initialize();

        });

        function initialize() {
            gerouRoutaParada = false;
            geocoder = new google.maps.Geocoder();
            directionsDisplay = new google.maps.DirectionsRenderer();

            var latlng = new google.maps.LatLng(-8.134740, -34.916501);
            var myOptions = {
                zoom: 17,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            directionsDisplay.setMap(map);

            //            var marker = new google.maps.Marker({
            //                position: new google.maps.LatLng(-8.134741, -34.916502),
            //                map: map,
            //                title: 'AEROPORTO/AFOGADOS',
            //                icon: "../../Content/Imagens/iconParada.png"
            //            });

            //            var janela = new google.maps.InfoWindow({
            //                content: 'Linha 232<br />AEROPORTO/AFOGADOS',
            //                size: new google.maps.Size(150, 150)
            //            });
            //                            title: 'Marcador',
            //              icon: "http://labs.google.com/ridefinder/images/mm_20_yellow.png"

            //Adicionando no on click marcador
            //            google.maps.event.addListener(marker, 'click', function () {
            //                janela.open(map, marker);
            //                //map.setZoom(8);
            //            });
            //google.maps.event.addListener(map, 'click', function () {
            //janela.open(map, janela);
            //});

            //detectBrowser();
            procurarParadasLinha();
            procurarTransportePorUsuario();
        }

        function procurarParadasLinha() {
            $.ajax({
                //Metodo utilizado
                type: "POST",
                //Url webservices
                url: "/ServiceData/ProcurarParadasPorLinha",
                contentType: "application/json",
                //String de dados enviada
                data: '{"idLinha":' + IdLinhaUsuarioLogado + '}',
                processData: false,
                //Inicio da funcao que requisita a resposta da pagina onde recebeu os dados
                success: function (json) {

                    AjaxSucceededParadas(json);

                },
                error: function (msg) {
                    alert("ERRO INESPERADO NO SERVIDOR. ");
                }
            });
        }

        function AjaxSucceededParadas(json_string) {
            //convertendo a string em objetos com o eval
            paradas_list = eval(json_string);

            for (var i = 0; i < paradas_list.length; i++) {
                balao_texto = "Parada de número: " + paradas_list[i].Numero + "<br />Tempo de espera: " + paradas_list[i].TempoChegadaOnibus;
                marcaPonto(paradas_list[i].Latitude, paradas_list[i].Longitude, "Parada de número: " + paradas_list[i].Numero, balao_texto, "../../Content/Imagens/iconParada.png");
            }
            if (gerouRoutaParada == false) {
                gerouRoutaParada = true;
                calcRoute(paradas_list);
            }
        }

        function procurarTransportePorUsuario() {
            if (gerouRoutaParada == false) {
                procurarParadasLinha();
            }

            $.ajax({
                //Metodo utilizado
                type: "POST",
                //Url webservices
                url: "/ServiceData/ProcurarTransporteUsuarioWeb",
                contentType: "application/json",
                //String de dados enviada
                //data: '{"idLinha":' + IdLinhaUsuarioLogado + ',"idUsuario":' + IdUsuarioLogado + '}',
                data: JSON.stringify({ IdUsuario: IdUsuarioLogado, idLinha: IdLinhaUsuarioLogado }),
                //JSON.stringify({ jewellerId: filter, locale: 'en-US' }
                processData: false,
                //Inicio da funcao que requisita a resposta da pagina onde recebeu os dados
                success: function (json) {

                    AjaxSucceededLocation(json);

                },
                error: function (msg) {
                    alert("ERRO INESPERADO NO SERVIDOR LOCATION. ");
                }
            });

            if (intervalFuncao) {
                clearTimeout(intervalFuncao);
                intervalFuncao = setTimeout("procurarTransportePorUsuario()", 10000);
            }
            else {
                intervalFuncao = setTimeout("procurarTransportePorUsuario()", 10000);
            } /**/
        }

        function AjaxSucceededLocation(json_string) {
            //convertendo a string em objetos com o eval
            //alert(json_string);
            //if (json_string != null) {

            //alert(json_string.Localizacao[0].Latitude);
            
            localizacao = eval(json_string);

            //alert(localizacao[0].Latitude);


            marcaPonto(localizacao[0].Latitude, localizacao[0].Longitude, "Onibus", "Velocidade: "  + localizacao[0].Velocidade, "../../Content/gifs/b_onibus.gif");
        }

        function calcRoute(paradas_list) {

            //var waypts = [];

            //            waypts.push({
            //                location: new google.maps.LatLng(paradas_list[10].Latitude, paradas_list[10].Longitude),
            //                stopover: true
            //            });

            //            for (var i = 0; i < paradas_list.length; i++) {

            //                waypts.push({
            //                    location: new google.maps.LatLng(paradas_list[i].Latitude, paradas_list[i].Longitude),
            //                    stopover: true
            //                });
            //            }

            //            for (var i in owt.stores.spotStore.data.map) {
            //                waypts.push({
            //                    location: new google.maps.LatLng(12.3, -33.6),
            //                    stopover: true
            //                });
            //                console.log(waypts);
            //            }
            var request = {
                origin: new google.maps.LatLng(paradas_list[0].Latitude, paradas_list[0].Longitude),
                destination: new google.maps.LatLng(paradas_list[paradas_list.length - 1].Latitude, paradas_list[paradas_list.length - 1].Longitude),
                //waypoints: waypts,
                //optimizeWaypoints: true,
                travelMode: google.maps.TravelMode.DRIVING
                //travelMode: google.maps.DirectionsTravelMode.DRIVING    
            };

            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });
        }
        ;

        function marcaPonto(latitude, longitude, dica, balaoTexto, iconePath) {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(latitude, longitude),
                map: map,
                title: dica,
                icon: iconePath
            });

            var janela = new google.maps.InfoWindow({
                content: balaoTexto,
                size: new google.maps.Size(150, 150)
            });
            //                            title: 'Marcador',
            //              icon: "http://labs.google.com/ridefinder/images/mm_20_yellow.png"

            //Adicionando no on click marcador
            google.maps.event.addListener(marker, 'click', function () {
                janela.open(map, marker);
                //map.setZoom(8);
            });
        } /**/

        function centerMap(latitude, longitude) {
            map.setCenter(new google.maps.LatLng(latitude, longitude));
        }
    </script>
    <style type="text/css">
        .style2
        {
            width: 10%;
        }
        .style3
        {
            width: 90%;
        }
    </style>
</head>
<body id="corpo2">
    <div id="topo">
        <asp:HyperLink ID="HyperLink8" runat="server" NavigateUrl="~/Views/UsuarioTransporte/MenuUsuario.aspx">
        <div id="logoTopo"></div>
        </asp:HyperLink>
        <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/Default.aspx">
        <div id="sair"></div>
        </asp:HyperLink>
    </div>
    <br />
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <table>
        <tr>
            <td>
            </td>
            <td class="style2">
            </td>
            <td class="style3">
                <asp:DropDownList ID="DropDownListLinhas" runat="server" Height="30px" Width="399px">
                </asp:DropDownList>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Button ID="Button1" runat="server" EnableTheming="True" OnClick="Button1_Click"
                    Text="Localizar" BackColor="#6ea954" BorderColor="#6ea954" ForeColor="White"
                    Height="30px" Width="100px" />
                <br />
                <asp:UpdateProgress ID="UpdateProgress1" runat="server">
                    <ProgressTemplate>
                        <asp:Image ID="Image2" runat="server" ImageUrl="~/Content/gifs/wait_gif.gif" />
                    </ProgressTemplate>
                </asp:UpdateProgress>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                </asp:UpdatePanel>
            </td>
        </tr>
        <tr>
            <td>
                <table>
                    <tr>
                        <td>
                            <asp:Image ID="ImgFotoUsuario" runat="server" Height="138px" Width="137px" ImageUrl="~/Content/Imagens/foto.jpg" />
                            <br />
                            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="MenuUsuarioAlterarFoto.aspx">Alterar foto</asp:HyperLink>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="LabelbemVindo" runat="server" Text="Bem vindo," Font-Bold="True" ForeColor="#000099"></asp:Label>
                            <br />
                            <asp:Label ID="LabelNomeUsuario" runat="server" Text="Label" Font-Bold="True" ForeColor="#000099"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <ul id="css3menu1" class="topmenu">
                                <li class="topfirst"><a href="MenuUsuarioDadosPessoais.aspx" title="Dados Pessoais"
                                    style="width: 118px;">Dados Pessoais</a></li>
                                <li class="topmenu"><a href="MenuUsuarioEndereco.aspx" title="Meu Endereço" style="width: 118px;">
                                    Meu Endereço</a></li>
                                <li class="topmenu"><a href="MenuUsuarioAlterarSenha.aspx" title="Alterar Senha"
                                    style="width: 118px;">Alterar Senha</a></li>
                                <li class="topmenu"><a href="MenuUsuarioLinha.aspx" title="Linhas de Ônibus" style="width: 118px;">
                                    Linhas de Ônibus</a></li>
                                <li class="topmenu"><a href="MenuUsuarioHorarios.aspx" title="Horarios" style="width: 118px;">
                                    Horarios</a></li>
                                <li class="toplast"><a href="MenuUsuarioMapa.aspx" title="Localizar Ônibus" style="width: 118px;
                                    color: #000; background-color: #d5e3e7">Localizar Ônibus</a></li>
                            </ul>
                        </td>
                    </tr>
                </table>
            </td>
            <td style="width: 10%">
            </td>
            <td style="width: 90%">
                <div id="map_canvas" style="width: 100%; height: 600px">
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
